﻿using System;
using System.Data;
using System.Data.OracleClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class SysManage_OrganSetup : UserPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            OrganDLL_Bind();
            OrganType_Bind();
            OrganList_Bind();            
        }
    }

    protected void BtnCreate_Click(object sender, EventArgs e)
    {
        if (!IFOrganNew())
        {
            JQFunction("$('#AddOrganDiv').dialog('open');$('#MsgDiv').show();$('#JQmsg').html('机构名称已存在！');$('#Organ_A').focus();");
            return;
        }
        string sqlStr = "U_ADD_ORGAN_P";
        OracleParameter[] _params = {
            new OracleParameter("V_ORGAN",OracleType.NVarChar,20),
            new OracleParameter("V_RGT",OracleType.Int32),
            new OracleParameter("V_TYPE",OracleType.VarChar,20)
        };
        _params[0].Value = Organ_A.Text.Trim();
        _params[1].Value = Int32.Parse(Upper_A.SelectedValue);
        _params[2].Value = Organ_Type_A.SelectedValue;
        int res = OracleHelper.ExecuteNonQuery(sqlStr, CommandType.StoredProcedure, _params);
        if (res > 0)
        {
            ReBind();          
        }
    }

    private bool IFOrganNew()
    {
        string sqlStr = "SELECT count(1) FROM u_organ_t WHERE organ = :organ AND if_valid = 'Y'";
        OracleParameter[] _params = {
                new OracleParameter(":organ",OracleType.NVarChar,20)
            };
        _params[0].Value = Organ_A.Text.Trim();
        return OracleHelper.ExecuteScalar(sqlStr, CommandType.Text, _params).ToString().Equals("0");
    }

    private void ReBind()
    {
        Organ_A.Text = "";
        OrganList_Bind();
        OrganDLL_Bind();
        OrganType_Bind();
        JQueryAlert("机构新增成功！");
    }

    private void OrganDLL_Bind()
    {
        string sqlStr = @"SELECT t1.space_organ,t2.rgt
                                  FROM (SELECT CONCAT(U_Repeat('　',(COUNT(t2.organ)-1)),t1.organ) AS space_organ,t1.organ
                                  FROM u_organ_t t1,u_organ_t t2
                                 WHERE t1.lft BETWEEN t2.lft AND t2.rgt
                                 GROUP BY t1.organ) t1
                                  LEFT JOIN u_organ_t t2
                                    ON t1.organ = t2.organ
                                 WHERE t2.if_valid = 'Y'
                                 ORDER BY t2.lft";
        Upper_A.DataSource = OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
        Upper_A.DataTextField = "space_organ";
        Upper_A.DataValueField = "rgt";
        Upper_A.DataBind();
        PreSetFirst();
    }

    private void OrganType_Bind()
    {
        string strSql = @"select data_code,data_name as organ_type from U_PUB_DATA_T WHERE data_type = 'organ_type' 
                                    AND if_valid = 'Y' ORDER BY order_num";
        Organ_Type_A.DataSource = OracleHelper.ExecuteDataSet(strSql, CommandType.Text, null);
        Organ_Type_A.DataTextField = "organ_type";
        Organ_Type_A.DataValueField = "data_code";
        Organ_Type_A.DataBind();
        Organ_Type_A.Items.Insert(0, new ListItem("请选择…", ""));
    }

    private DataTable GetManagerByOrgan(string argOrgan)
    {
        string sqlStr = @"SELECT login_name,real_name FROM u_user_info_t 
                                    where organ = :organ and if_valid = 'Y' order by login_name";
        OracleParameter[] _params = {
            new OracleParameter(":organ",OracleType.NVarChar,20)
        };
        _params[0].Value = argOrgan;
        return OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, _params).Tables[0];
    }

    private void PreSetFirst()
    {
        if (Upper_A.Items.Count == 0)
        {
            Upper_A.Items.Insert(0, new ListItem("最高节点", "1"));
        }
        else
        {
            Upper_A.Items.Insert(0, new ListItem("请选择…", ""));            
        }
        Upper_A.SelectedIndex = 0;
    }

    private void OrganList_Bind()
    {
        string sqlStr = @"SELECT t1.space_organ as organ,t2.rgt,t2.if_valid,nvl(t3.real_name,'') as manager,t4.data_name as organ_type
                                    ,nvl(t3.login_name,'') as login_name 
                                  FROM (SELECT CONCAT(U_Repeat('　',(COUNT(t2.organ)-1)),t1.organ) AS space_organ,t1.organ
                                  FROM u_organ_t t1,u_organ_t t2
                                 WHERE t1.lft BETWEEN t2.lft AND t2.rgt
                                 GROUP BY t1.organ) t1
                                  LEFT JOIN u_organ_t t2
                                    ON t1.organ = t2.organ
                                  LEFT JOIN u_user_info_t t3
                                    ON t2.manager = t3.login_name
                                  LEFT JOIN u_pub_data_t t4
                                    ON t4.data_type = 'organ_type'
                                   AND t4.data_code = t2.organ_type
                                WHERE t2.if_valid = 'Y'
                                 ORDER BY t2.lft";
        OrganList.DataSource = OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
        OrganList.DataBind();
    }

    protected void OrganList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Charge")
        {
            DisableOrgan(e.CommandArgument.ToString());
        }
        else if (e.CommandName == "DeleteOrgan")
        {
            if (!IFOrganEmpty(e.CommandArgument.ToString()))
            {
                JQueryAlert("该机构或者其下级机构包含有用户所以无法直接删除！");
                return;
            }
            DeleteOrgan(e.CommandArgument.ToString());
        }
    }

    private void DisableOrgan(string argOrgan)
    {
        string sqlStr = "U_DISABLE_ORGAN_P";
        OracleParameter[] _params = {
                new OracleParameter("V_ORGAN",OracleType.NVarChar,20)
            };
        _params[0].Value = argOrgan.Trim();
        int res = OracleHelper.ExecuteNonQuery(sqlStr, CommandType.StoredProcedure, _params);
        if (res > 0)
        {
            OrganList_Bind();
            OrganDLL_Bind();
            JQueryAlert("该机构已经禁用！");
        }
    }

    private void DeleteOrgan(string argOrgan)
    {
        string sqlStr = "U_DELETE_ORGAN_P";
        OracleParameter[] _params = {
                new OracleParameter("V_ORGAN",OracleType.NVarChar,20)
            };
        _params[0].Value = argOrgan.Trim();
        int res = OracleHelper.ExecuteNonQuery(sqlStr, CommandType.StoredProcedure, _params);
        if (res > 0)
        {
            OrganList_Bind();
            OrganDLL_Bind();
            JQueryAlert("机构删除成功！");
        }
    }

    private bool IFOrganEmpty(string argOrgan)
    {
        string sqlStr = @"select count(1) from u_user_info_t
                                    where organ in (select organ from u_organ_t t1 where exists (
                                    select 1 from u_organ_t t2 where organ = :organ
                                    and t1.lft between t2.lft and t2.rgt))";
        OracleParameter[] _params = {
                new OracleParameter(":organ",OracleType.NVarChar,20)
            };
        _params[0].Value = argOrgan.Trim();
        return OracleHelper.ExecuteScalar(sqlStr, CommandType.Text, _params).ToString().Equals("0");
    }

    protected void OrganList_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string sqlstr = @"UPDATE u_organ_t SET manager=:manager WHERE organ=:organ ";
        DropDownList ddl = OrganList.Rows[e.RowIndex].FindControl("Manager_D") as DropDownList;
        OracleParameter[] _params = {
            new OracleParameter(":manager",OracleType.VarChar,16),
            new OracleParameter(":organ",OracleType.NVarChar,20)
        };
        _params[0].Value = ddl.SelectedValue;
        _params[1].Value = OrganList.DataKeys[e.RowIndex].Value.ToString().Trim();
        int res = OracleHelper.ExecuteNonQuery(sqlstr, CommandType.Text, _params);
        if (res > 0)
        {
            OrganList.EditIndex = -1;
            OrganList_Bind();
            JQueryAlert("主负责人更新成功!");
        }    
    }

    protected void OrganList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        OrganList.EditIndex = e.NewEditIndex;
        OrganList_Bind();
    }

    protected void OrganList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        OrganList.EditIndex = -1;
        OrganList_Bind();
    }

    protected void OrganList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.FindControl("Manager_D") != null)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("Manager_D");
                ddl.DataSource = GetManagerByOrgan(OrganList.DataKeys[e.Row.RowIndex].Value.ToString().Trim());
                ddl.DataTextField = "real_name";
                ddl.DataValueField = "login_name";
                ddl.DataBind();
                ddl.Items.Insert(0, new ListItem("—请选择—", " "));
                ddl.SelectedValue = DataBinder.Eval(e.Row.DataItem, "login_name").ToString();
            }
        }
    }
}
